package api

import (
	"github.com/gin-gonic/gin"
	"server/internal/middleware"
	"server/internal/model"
	"server/internal/pkg/response"
	"server/internal/services"
	"strconv"
)

// AreaApi 地区管理
var AreaApi = new(areaApi)

type areaApi struct {
	model.Area
}

// Router 路由
func (a areaApi) Router(r *gin.RouterGroup) {
	api := r.Group("/area", middleware.LoginVerification, middleware.PermissionVerification)
	//验证权限
	api.GET("/list", a.list)
	api.GET("/edit", a.detail)
	api.POST("/add", a.add)
	api.POST("/edit", a.edit)
	api.POST("/del", a.del)

	//不验证权限
	api2 := r.Group("/area", middleware.LoginVerification)
	api2.GET("/get_select", a.getSelect)
	api2.GET("/get_select_gradually", a.getSelectGradually)

}

// List 列表
func (a areaApi) list(c *gin.Context) {

	response.SuccessList(c, services.Area.GetTreeList(0), 0)
}

// Detail 单条
func (a areaApi) detail(c *gin.Context) {
	id := c.Query("id")

	detail := services.Area.GetById(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a areaApi) add(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	_, err := services.Area.Create(a.Area)
	if err != nil {
		response.Error(c, "添加失败", err.Error())
	} else {
		response.Success(c, "", "添加成功")
	}
}

// Edit 编辑
func (a areaApi) edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	_, err := services.Area.Update(a.Area)
	if err != nil {
		response.Error(c, "编辑失败")
	} else {
		response.Success(c, "", "编辑成功")
	}
}

// Del 删除
func (a areaApi) del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	if services.Area.Delete(param.Ids) != nil {
		response.Error(c, "删除失败")
	} else {
		response.Success(c, "", "删除成功")
	}
}

// GetSelect 远程下啦
func (a areaApi) getSelect(c *gin.Context) {

	response.Success(c, services.Area.Select(0), "")
}

// GetSelectGradually 远程下啦 逐级查看
func (a areaApi) getSelectGradually(c *gin.Context) {
	pid := c.Query("pid")
	if pid == "" {
		pid = "0"
	}
	pids, _ := strconv.Atoi(pid)
	response.Success(c, services.Area.GetSelectGradually(pids), "")
}
